<?php
namespace App\Services;

use App\Models\WxShorturl;
use Illuminate\Support\Facades\DB;

/**
 * 短链接服务类
 * @package App\Services
 */
class WxShorturlService
{
    /**
     * 构造函数
     */
    public function __construct()
    {

    }

    /**
     * 保存短链接数据
     * @param $request
     * @return bool
     * @throws \Exception
     */
    public function saveData($request)
    {
        Db::beginTransaction();
        try{
            if ($request->id){
                $shorturlModle = WxShorturl::findOrFail($request->id);
            }else{
                $shorturlModle = new WxShorturl;
            }
            $shorturlModle->name = $request->name ?? '';
            if ($shorturlModle->long_url != $request->long_url){
                $shorturlModle->long_url = $request->long_url;
                //生成短链接
                $app = EasyWechat::officialAccount();
                $apiRs = $app->url->shorten($request->long_url);
                //检查微信接口返回结果
                WxErrorService::checkApiResponse($apiRs);
                $shorturlModle->short_url = $apiRs['short_url'] ?? '';
            }
            if (empty($shorturlModle->short_url)){
                throw new \Exception('生成短链接为空');
            }
            $shorturlModle->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 删除短链接数据
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public function del($id)
    {
        Db::beginTransaction();
        try {
            $shorturlModle = WxShorturl::findOrFail($id);
            if (empty($shorturlModle)){
                throw new \Exception('短链接不存在');
            }

            $shorturlModle->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }
}